import os
from flask import Flask
import pika
import pymysql
from flask import jsonify
import redis
from minio import Minio
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route('/')
def home():
    return "Backend is running"

# 配置 MySQL 连接
db_config = {
    'host': 'mysql',
    'port': 3306,
    'user': 'root',
    'password': 'Admin@123',
    'database': 'test_db',
    'charset': 'utf8mb4'
}
# 测试 MySQL 连接
@app.route('/test_db')
def test_db():
    try:
        conn = pymysql.connect(**db_config)
        cursor = conn.cursor()
        cursor.execute("SELECT DATABASE();")
        result = cursor.fetchone()
        print(f"Connected to {result[0]} database")
        return jsonify({"message": f"Connected to {result[0]} database"})
    except pymysql.connector.Error as err:
        print(f"Database connection failed: {str(err)}")
        return jsonify({"error": str(err)})

# 创建 MySQL 表
@app.route('/create_table')
def create_table():
    conn = pymysql.connect(**db_config)
    cursor = conn.cursor()
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS users (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(255),
            email VARCHAR(255)
        );
    """)
    conn.commit()
    conn.close()
    return jsonify({"message": "Table created"})

# 配置访问 RabbitMQ 连接
rabbitmq_host = 'rabbitmq'
queue_name = 'test_queue'

# 配置 RabbitMQ 生产者
@app.route('/send_message')
def send_message():
    credentials = pika.PlainCredentials('admin', 'Admin@123')
    connection = pika.BlockingConnection(pika.ConnectionParameters(host=rabbitmq_host, port=5672, credentials=credentials, virtual_host='/'))
    channel = connection.channel()

    channel.queue_declare(queue=queue_name, durable=True)

    message = "Hello from RabbitMQ!"
    channel.basic_publish(
        exchange='',
        routing_key=queue_name,
        body=message,
        properties=pika.BasicProperties(
            delivery_mode=2,  # 使消息持久化
        ))
    # print("Send message to RabbitMQ")
    connection.close()
    return jsonify({"message": "Message sent to RabbitMQ"})

# 配置 RabbitMQ 消费者

messages = []

def callback(ch, method, properties, body):
    messages.append(body.decode(''))

def start_consuming():
    credentials = pika.PlainCredentials('admin', 'Admin@123')
    connection = pika.BlockingConnection(pika.ConnectionParameters(host='rabbitmq', port=5672, credentials=credentials, virtual_host='/'))
    channel = connection.channel()

    channel.queue_declare(queue=queue_name, durable=True)
    channel.basic_consume(queue=queue_name, on_message_callback=callback, auto_ack=True)
    channel.start_consuming()

# 从rabbitmq队列中接收消息
@app.route('/receive_message')
def receive_message():
    return jsonify({"message": messages})

# 配置 Redis 连接
redis_client = redis.StrictRedis(host='redis', port=6379, db=0)

@app.route('/cache_test')
def cache_test():
    redis_client.set('message', 'Hello from Redis!')
    message = redis_client.get('message').decode('utf-8')
    return jsonify({"message": message})

#集成 MinIO 数据备份

# 配置 MinIO 客户端
minio_client = Minio(
    'minio:9000',
    access_key='admin',
    secret_key='Admin@123',
    secure=False
)

# 创建 MinIO 存储桶
bucket_name = 'mybucket'
if not minio_client.bucket_exists(bucket_name):
    minio_client.make_bucket(bucket_name)
    print(f"Bucket {bucket_name} created successfully")
else:
    print(f"Bucket {bucket_name} already exists")

@app.route('/upload_file')
def upload_file():
    # 假设我们要上传一个简单的文本文件
    with open('backup.txt', 'w') as file:
        file.write('Hello, this is a file to be backed up!')
    destination_file = "backup.txt"
    source_file = "backup.txt"
    
    # 上传文件到 MinIO
    minio_client.fput_object(
        bucket_name, destination_file, source_file,
    )
    
    return jsonify({"message": "File uploaded to MinIO"})


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000, debug=True)
